<template>
  <div class="demo-spin-article">
    <div style="height: 15px; width: 100%"></div>
    <Row @keydown.enter.native="handleSearch">
      <Form
        ref="searchForm"
        :model="searchForm"
        inline
        :label-width="85"
        class="search-form"
      >
        <FormItem label="车牌号" prop="vehicleNum">
          <Select
            transfer
            v-model="searchForm.vehicleNum"
            filterable
            clearable
            @on-query-change="changeDriver"
            placeholder="请选择车牌号"
            style="width: 158px"
          >
            <Option
              v-for="(item, index) in licenseList"
              :key="index"
              :value="item.gpsEquipment"
            >
              {{ item.vehicleNum }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="开始时间">
          <DatePicker
            clearable
            type="datetime"
            placement="bottom-end"
            placeholder="请选择开始时间"
            style="width: 200px"
            format="yyyy-MM-dd HH:mm:ss"
            v-model="searchForm.startTime"
            @on-change="changeStartTime"
          ></DatePicker>
        </FormItem>
        <FormItem label="结束时间">
          <DatePicker
            clearable
            type="datetime"
            placement="bottom-end"
            placeholder="请选择结束时间"
            style="width: 200px"
            format="yyyy-MM-dd HH:mm:ss"
            v-model="searchForm.endTime"
            @on-change="changeEndTime"
          ></DatePicker>
        </FormItem>
        <span style="margin-left: 35px" class="br">
          <Button @click="handleSearch" type="primary" icon="ios-search"
            >搜索</Button
          >
          <Button @click="handleReset">重置</Button>
        </span>
      </Form>
    </Row>

    <div class="springFrame">
      <div id="trajectory-map"></div>
    </div>
     <Spin size="large" fix v-if="spinShow"></Spin>
  </div>
</template>

<script>
import {
  historyVehicle, // 历史轨迹 --- 获取车牌号
  getHistoryTracks, // 获取车辆历史轨迹
} from "@/api/map";
import beginImg from "@/assets/begin_icon.png";
import endImg from "@/assets/end_icon.png";
export default {
  data() {
    return {
      spinShow:false,
      searchForm: {
        vehicleNum: "",
        gpsEquipment: "",
        startTime: "",
        endTime: "",
      },
      loadinTiem: "",
      unload: "",
      licenseList: [],
      //
      map: "",
      driverData: {},
    };
  },
  mounted() {
    this.map = new AMap.Map("trajectory-map", {
      resizeEnable: true,
      center: [116.478935, 39.997761],
      zoom: 5,
    });
  },
  methods: {
    changeStartTime(val) {
      this.searchForm.startTime = val;
    },
    changeEndTime(val) {
      this.searchForm.endTime = val;
    },
    //搜索
    handleSearch() {
      if (
        this.searchForm.vehicleNum &&
        this.searchForm.startTime &&
        this.searchForm.endTime
      ) {
        this.spinShow=true
        getHistoryTracks(this.searchForm).then((res) => {
           this.spinShow=false
          if (res.success) {
            if (res.result.length > 1) {
              let array = [];
              for (let i = 0; i < res.result.length; i++) {
                let arr = [];
                arr[0] = res.result[i].lon;
                arr[1] = res.result[i].lat;
                array.push(arr);
                if (res.result.length - 1 == i) {
                  this.createMap(array);
                }
              }
            } else {
              return this.$Message.warning("暂无数据");
            }
          } else {
            this.$Message.error(res.message);
          }
        });
      } else {
        return this.$Message.warning("请输入搜索项");
      }
    },
    // 驾驶驾驶员输入框编辑
    changeDriver(val) {
      if (val) {
        let text = /^[\u4e00-\u9fa5]{0,}$/;
        let reg = /^[1-9]\d*$/;
        if (text.test(val)) {
          if (val.length > 0) {
            this.$set(this.driverData, "vehicleNum", val);
            this.getDriverList();
          }
        }
        if (reg.test(val)) {
          if (val.length > 0) {
            this.$set(this.driverData, "vehicleNum", val);
            this.getDriverList();
          }
        }
      }
    },
    //获取未绑定驾驶员列表接口
    getDriverList() {
      historyVehicle(this.driverData).then((res) => {
        if (res.code == 200) {
          this.licenseList = res.result;
          this.driverData.searchContent = "";
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    //重置
    handleReset() {
      this.searchForm.startTime = "";
      this.searchForm.endTime = "";
      this.loadinTiem = "";
      this.searchForm.vehicleNum = "";
    },
    //时间
    loadingDate(val) {
      this.searchForm.startTime = val[0];
      this.searchForm.endTime = val[1];
    },
    //1.创建map对象
    createMap(val) {
      this.map = new AMap.Map("trajectory-map", {
        resizeEnable: true,
        center: val[0],
        zoom: 5,
      });
      let _this = this;
      AMap.plugin(["AMap.ToolBar"], function () {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        _this.map.addControl(
          new AMap.ToolBar({
            // 简易缩放模式，默认为 false
            liteStyle: true,
          })
        );
      });

      AMapUI.load(
        ["ui/misc/PathSimplifier", "lib/$"],
        function (PathSimplifier, $) {
          if (!PathSimplifier.supportCanvas) {
            alert("当前环境不支持 Canvas！");
            return;
          }
          var defaultRenderOptions = {
            renderAllPointsIfNumberBelow: -1, //绘制路线节点，如不需要可设置为-1
            pathLineStyle: {
              //路线样式设置
              lineWidth: 2,
              strokeStyle: "#3CB371",
              borderWidth: 1,
              borderStyle: "#eeeeee",
              dirArrowStyle: false,
            },
            startPointStyle: {
              //起点
              radius: 8,
              fillStyle: "#3CB371",
              lineWidth: 2,
              strokeStyle: "#eeeeee",
            },
            endPointStyle: {
              //终点
              radius: 8,
              fillStyle: "#3CB371",
              lineWidth: 2,
              strokeStyle: "#eeeeee",
            },
          };
          var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            //autoSetFitView:false,
            map: _this.map, //所属的地图实例
            getPath: function (pathData, pathIndex) {
              return pathData.path;
            },
            getHoverTitle: function (pathData, pathIndex, pointIndex) {
              if (pointIndex >= 0) {
                //point
                return (
                  pathData.name +
                  "，点：" +
                  pointIndex +
                  "/" +
                  pathData.path.length
                );
              }
              return pathData.name + "，点数量" + pathData.path.length;
            },
            renderOptions: defaultRenderOptions,
          });
          window.pathSimplifierIns = pathSimplifierIns;
          //设置数据
          pathSimplifierIns.setData([
            {
              name: "路线0", //设置路线的初始地
              path: val,
            },
          ]);
          var navg1 = pathSimplifierIns.createPathNavigator(0, {
            loop: false,
            speed: 10000,
            pathNavigatorStyle: {
              //经过路径的样式
              pathLinePassedStyle: {
                lineWidth: 6,
                strokeStyle: "#087ec4",
                dirArrowStyle: {
                  stepSpace: 15,
                  strokeStyle: "#FFFFFF",
                },
              },
            },
          });
          navg1.start();
        }
      );
      // onRegeocodeSearched
      //当前位置
      let k = val.length - 1;
      let lnglat = val[k];
      this.getPosition(lnglat);
      //起点

      var beginAddressMap = new AMap.Marker({
        position: new AMap.LngLat(val[0].join(",")), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: new AMap.Icon({
          image: beginImg,
          size: new AMap.Size(52, 52), //图标大小
          imageSize: new AMap.Size(42, 42),
        }),
      });
      this.map.add(beginAddressMap);
      // // console.log(val[0].join(","));
      // console.log(val[val.length-2]);
      //终点
      var endAddressMap = new AMap.Marker({
        position: new AMap.LngLat(val.slice(-1)), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: new AMap.Icon({
          image: endImg,
          size: new AMap.Size(52, 52), //图标大小
          imageSize: new AMap.Size(42, 42),
        }),
      });
      this.map.add(endAddressMap);
    },
    getPosition(k) {
      AMap.plugin("AMap.Geocoder", () => {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: "010",
        });
        geocoder.getAddress(k, (status, result) => {
          if (status === "complete" && result.info === "OK") {
            // result为对应的地理位置详细信息
            this.caraddress = result.regeocode.formattedAddress;
            // if (
            //   result.regeocode.formattedAddress == "" ||
            //   result.regeocode.formattedAddress == null
            // ) {
            //   this.caraddress = "暂无车辆轨迹";
            // } else {

            // }
          }
        });
      });
    },
  },
};
</script>

<style>
#trajectory-map {
  height: 820px;
}
.springFrame {
  height: 650x;
  width: 95%;
  overflow: hidden;
}
</style>